package com.small.nacos.config.server.utils;

import small.common.core.constants.CommonConstants;
import small.common.crypto.util.KeyUtil;
import small.common.core.util.StringUtil;
import com.small.nacos.config.server.service.ConfigCacheService;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static small.common.core.constants.CommonConstants.WORD_SEPARATOR;

public class MD5Util {

    public static List<String> compareMd5(Map<String, String> clientMd5Map) {
        List<String> updateList = new ArrayList();
        for (Map.Entry<String, String> entry : clientMd5Map.entrySet()) {
            String key = entry.getKey();
            String md5 = entry.getValue();
            boolean uptodate = ConfigCacheService.isUptodate(key, md5);
            if (uptodate) {
                updateList.add(key);
            }
        }
        return updateList;
    }


    /**
     * 拼接key为字符串
     * @param changedGroupKeys
     * @return
     * @throws IOException
     */
    public static String compareMd5ResultString(List<String> changedGroupKeys) throws IOException {
        if (null == changedGroupKeys) {
            return "";
        }

        StringBuilder sb = new StringBuilder();

        for (String groupKey : changedGroupKeys) {
            String[] dataIdGroupId = KeyUtil.parseKey(groupKey);
            sb.append(dataIdGroupId[0]);
            sb.append(CommonConstants.WORD_SEPARATOR);
            sb.append(dataIdGroupId[1]);
            // if have tenant, then set it
            if (dataIdGroupId.length == 3) {
                if (StringUtil.isNotBlank(dataIdGroupId[2])) {
                    sb.append(WORD_SEPARATOR);
                    sb.append(dataIdGroupId[2]);
                }
            }
            sb.append(CommonConstants.LINE_SEPARATOR);
        }

        // To encode WORD_SEPARATOR and LINE_SEPARATOR invisible characters, encoded value is %02 and %01
        return URLEncoder.encode(sb.toString(), "UTF-8");
    }

}
